"""
文件上传路由
"""
from fastapi import APIRouter, UploadFile, File, HTTPException, Depends
from fastapi.responses import JSONResponse
import os
import logging
from datetime import datetime
from sqlalchemy.orm import Session

from app.core.response import create_response
from app.core.database import get_db, engine
from app.models.upload import Base, FileUpload

router = APIRouter()
logger = logging.getLogger(__name__)

# 确保上传目录存在
UPLOAD_DIR = "uploads/data"
os.makedirs(UPLOAD_DIR, exist_ok=True)

# 创建数据库表
Base.metadata.create_all(bind=engine)

# 原始端点
@router.get("/files/list", tags=["Upload"])
async def get_uploaded_files(db: Session = Depends(get_db)):
    """
    获取已上传文件列表
    
    Returns:
        已上传文件的列表
    """
    try:
        # 从数据库获取所有文件记录，按上传时间倒序排列
        files = db.query(FileUpload).order_by(FileUpload.upload_time.desc()).all()
        
        # 转换为响应格式
        file_list = [
            {
                "id": file.id,
                "filename": file.filename,
                "original_filename": file.original_filename,
                "size": file.file_size,
                "upload_time": file.upload_time.isoformat(),
                "file_path": file.file_path,
                "file_type": file.file_type,
                "status": file.status
            }
            for file in files
        ]
        
        logger.info(f"获取文件列表成功，共{len(file_list)}个文件")
        
        return create_response(
            data={
                "files": file_list,
                "total": len(file_list)
            },
            message="获取文件列表成功"
        )
    except Exception as e:
        logger.error(f"获取文件列表失败: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=500,
            detail={
                "status": "error",
                "error": {
                    "code": "FETCH_FAILED",
                    "message": "获取文件列表失败",
                    "details": str(e)
                },
                "timestamp": datetime.now().isoformat()
            }
        )


# 兼容/api/files/list的端点
@router.get("/files/list", tags=["Upload"])
async def get_files_list(db: Session = Depends(get_db)):
    """
    兼容旧版API的文件列表端点
    与/data/list功能相同，用于支持/api/files/list请求
    """
    # 直接调用现有的get_uploaded_files函数
    return await get_uploaded_files(db)


@router.post("/data", tags=["Upload"])
async def upload_data_file(file: UploadFile = File(...), db: Session = Depends(get_db)):
    """
    上传数据文件接口
    
    Args:
        file: 要上传的文件
    
    Returns:
        包含上传状态和文件信息的响应
    """
    logger.info(f"开始处理文件上传请求: {file.filename}")
    logger.info(f"文件MIME类型: {file.content_type}")
    try:
        # 生成唯一文件名，避免覆盖
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        file_extension = os.path.splitext(file.filename)[1]
        new_filename = f"{timestamp}_{file.filename}"
        file_path = os.path.join(UPLOAD_DIR, new_filename)
        logger.info(f"生成目标文件路径: {file_path}")
        
        # 保存文件
        logger.info("开始读取文件内容...")
        contents = await file.read()
        logger.info(f"文件读取完成，大小: {len(contents)} 字节")
        
        logger.info(f"开始写入文件到: {file_path}")
        with open(file_path, "wb") as f:
            f.write(contents)
        logger.info(f"文件写入完成")
        
        # 提取文件类型
        file_type = file.content_type if file.content_type else os.path.splitext(file.filename)[1].lower()
        logger.info(f"文件类型: {file_type}")
        
        # 保存文件信息到数据库
        logger.info("开始保存文件信息到数据库...")
        db_file = FileUpload(
            filename=new_filename,
            original_filename=file.filename,
            file_path=file_path,
            file_size=len(contents),
            file_type=file_type,
            status="success"
        )
        db.add(db_file)
        logger.info("执行数据库提交...")
        db.commit()
        logger.info("执行数据库刷新...")
        db.refresh(db_file)
        
        logger.info(f"文件信息已保存到数据库，ID: {db_file.id}")
        
        # 构建响应数据
        response_data = {
            "id": db_file.id,
            "filename": new_filename,
            "original_filename": file.filename,
            "size": len(contents),
            "upload_time": db_file.upload_time.isoformat(),
            "file_path": file_path,
            "file_type": file_type
        }
        logger.info(f"准备返回响应数据: {response_data}")
        
        # 返回成功响应
        response = create_response(
            data=response_data,
            message="文件上传成功，信息已保存到数据库"
        )
        logger.info("响应已生成，准备返回给客户端")
        return response
        
    except Exception as e:
        logger.error(f"文件上传失败: {str(e)}", exc_info=True)
        logger.error(f"异常类型: {type(e).__name__}")
        import traceback
        logger.error(f"完整异常栈: {traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail={
                "status": "error",
                "error": {
                    "code": "UPLOAD_FAILED",
                    "message": "文件上传失败",
                    "details": str(e)
                },
                "timestamp": datetime.now().isoformat()
            }
        )